package com.surprise.es.service;

import java.util.List;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.springframework.stereotype.Service;

import com.surprise.base.bo.IdEntity;
import com.surprise.base.util.JacksonUtils;

/**
 * ESIndexService.java
 * @author nick
 * 2015年3月9日
 */
@Service
public class ESIndexService {
    /**
     * batch index docs
     * @param client
     * @param index
     * @param type
     * @param bos
     * @throws ElasticsearchException
     */
    public <T extends IdEntity> void batchIndex(Client client, String index, String type, List<T> bos) throws ElasticsearchException {
        BulkRequestBuilder request = client.prepareBulk();
        for(T bo : bos) {
            request.add(client.prepareIndex(index, type, bo.getId()+"").setSource(JacksonUtils.toJson(bo)));
        }
        BulkResponse response = request.execute().actionGet();
        if(response.hasFailures()) {
            for(T bo : bos) {
                index(client, index, type, bo);
            }
        }
    }
    
    /**
     * index a doc
     * @param client
     * @param index
     * @param type
     * @param bo
     * @return version of document in es
     * @throws ElasticsearchException
     */
    public <T extends IdEntity> long index(Client client, String index, String type, T bo) throws ElasticsearchException {
        IndexResponse response = client.prepareIndex(index, type, bo.getId()+"").setSource(JacksonUtils.toJson(bo)).execute().actionGet();
        return response.getVersion();
    }
}
